<?php
declare (strict_types = 1);

namespace app\middleware;

use think\Response;

/**
 * CORS跨域中间件
 * Class Cors
 * @package app\middleware
 */
class Cors
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 记录请求信息
        \think\facade\Log::info('CORS中间件 - 请求信息', [
            'method' => $request->method(),
            'url' => $request->url(),
            'headers' => $request->header(),
            'params' => $request->param()
        ]);

        // 获取请求来源
        $origin = $request->header('Origin');
        \think\facade\Log::info('CORS中间件 - 请求来源', ['origin' => $origin]);

        $allowedOrigins = [
            'http://localhost:8001',
            'http://localhost:8080',
            'http://localhost:3000',
            'http://localhost:8000',
            'http://127.0.0.1:8001',
            'http://127.0.0.1:8080',
            'http://127.0.0.1:3000',
            'http://127.0.0.1:8000',
            'http://192.168.110.8:8001',
            'http://192.168.110.8:8000',
            'http://tp.ml.com',
            'http://localhost'
        ];
        
        \think\facade\Log::info('CORS中间件 - 请求来源检查', [
            'origin' => $origin,
            'allowedOrigins' => $allowedOrigins,
            'inArray' => in_array($origin, $allowedOrigins)
        ]);
        
        $allowOrigin = in_array($origin, $allowedOrigins) ? $origin : 'http://localhost:8001';
        $allowHeaders = 'Content-Type, Authorization, X-Requested-With, Access-Token';
        
        \think\facade\Log::info('CORS中间件 - 选择的Origin', [
            'origin' => $origin,
            'allowOrigin' => $allowOrigin,
            'allowHeaders' => $allowHeaders
        ]);
        
        \think\facade\Log::info('CORS中间件 - 配置信息', [
            'allowedOrigins' => $allowedOrigins,
            'selectedOrigin' => $allowOrigin,
            'allowHeaders' => $allowHeaders
        ]);
        
        // 处理预检请求
        if ($request->method() == 'OPTIONS') {
            \think\facade\Log::info('CORS中间件 - 处理预检请求');
            
            // 直接返回CORS响应，不调用下一个中间件
            $response = response('', 204);
            
            // 强制设置CORS头部
            $headers = [
                'Access-Control-Allow-Origin' => $allowOrigin,
                'Access-Control-Allow-Methods' => 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
                'Access-Control-Allow-Headers' => $allowHeaders,
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Max-Age' => '86400',
                'X-Debug-ThinkPHP' => 'true',
                'X-Debug-Origin' => $origin ?: 'null',
                'X-Debug-Headers' => $allowHeaders
            ];
            
            $response->header($headers);
            
            \think\facade\Log::info('CORS中间件 - 预检响应头', $headers);
            return $response;
        } else {
            \think\facade\Log::info('CORS中间件 - 处理实际请求');
            
            $response = $next($request);
            
            // 为实际请求设置CORS头
            $headers = [
                'Access-Control-Allow-Origin' => $allowOrigin,
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Allow-Headers' => $allowHeaders,
                'X-Debug-ThinkPHP' => 'true',
                'X-Debug-Origin' => $origin ?: 'null'
            ];
            
            $response->header($headers);
            
            \think\facade\Log::info('CORS中间件 - 实际响应头', $headers);
            \think\facade\Log::info('CORS中间件 - 响应状态', [
                'status' => $response->getCode(),
                'content' => $response->getContent()
            ]);
            
            return $response;
        }
    }
}